﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Text;

namespace pmf
{
    static class Program
    {
        public static Config config = null;

        public static string configFileName
        {
            get
            { 
                return Path.Combine(SafeDirectory.inst.getCurrent(), "config.txt");
            }
        }

        [STAThread]
        static int Main(string[] args)
        {
            // manejo de excepciones
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.ThreadException +=
                new ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            // logueo inicio
            Logger.general.loguear("pmf iniciado");

            // cargo la configuracion
            if (!ConfigManager.cargarConfiguracion<Config>(ref config, configFileName))
            {
                Logger.general.loguear("pmf bad conf");
                Logger.general.loguear("pmf terminado con error");
                return -1;
            }

            // levanto FrmMain
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FrmMain());

            // guardo la configuración
            ConfigManager.saveConfig<Config>(config, configFileName);

            // logueo fin
            Logger.general.loguear("pmf terminado");

            // chau ok
            return 0;
        }

        static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            StringBuilder sbMensaje = new StringBuilder();
            sbMensaje.AppendLine("Application ThreadException (UI)");
            sbMensaje.AppendLine(e.Exception.ToString());
            Logger.general.loguear(sbMensaje.ToString());
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            StringBuilder sbMensaje = new StringBuilder();
            sbMensaje.AppendLine("Current Domain UnhandledException");
            if (e.ExceptionObject is Exception)
                sbMensaje.AppendLine(((Exception)e.ExceptionObject).ToString());
            Logger.general.loguear(sbMensaje.ToString());
        }
    }
}
